from logging import getLogger

from zope.interface import Interface, implements
from zope.configuration import config, fields
from zope.schema import TextLine, Int, Bool, Object
from zope.component import getGlobalSiteManager

from meercat.interfaces import IOrderedRegistry
from meercat.base.registry import OrderedRegistry
from meercat.base.zcml import IRegistryItemSchema
from meercat.harvester.base.interfaces import IHarvester
from meercat.harvester.base.zcml import IFileSourceContext
from meercat.harvester.metalib.harvester import MetalibHarvester



log = getLogger('meercat.harvester.metalib.zcml')

registry = getGlobalSiteManager()

class IHarvesterSchema(Interface):
    name = TextLine(
        title=u'Name',
        description=u'Name to use for registering the utility',
        required=True)
    
    source = TextLine(
        title=u'Source',
        description=u'The source name for the harvester (defaults to name)',
        required=False)


class HarvesterHandler(config.GroupingContextDecorator):
    implements(config.IConfigurationContext, IHarvesterSchema, IFileSourceContext)
    
    def __init__(self, context, name, **kwargs):
        log.debug('%s.__init__(%s,...)' % (str(self),str(context),))
        self.context = context
        self.name = name
        
        self.kwargs = kwargs
    
    def before(self):
        log.debug('%s.before()' % (str(self),))
        super(HarvesterHandler,self).before()
        self.harvester = registry.queryUtility(IHarvester, self.name, None)
        if self.harvester is None:
            self.harvester = MetalibHarvester(self.kwargs.get('source', self.name))
        
        if not isinstance(self.harvester, MetalibHarvester):
            raise TypeError('Invalid harvester type registered as %s' % (str(self.name),))
        
    
    def after(self):
        log.debug('%s.after()' % (str(self),))
        super(HarvesterHandler,self).after()
        
        registry.registerUtility(self.harvester, IHarvester, self.name)
    
    def getFileSource(self):
        return self.harvester.getFileSource()
    
    def setFileSource(self, source):
        return self.harvester.setFileSource(source)
